<?php defined('SYSPATH') or die('No direct script access.');
/**
 * $Id: post.php 50 2008-07-27 09:06:29Z geertdd $
 *
 * @package    PianissiBoard
 * @author     Geert De Deckere
 */
class Post_Model extends Model {

	/**
	 * Gets (all) the posts.
	 *
	 * @param   array    query settings (topic_id, limit, offset)
	 * @return  array
	 */
	public function get($config = array())
	{
		// Build query
		$sql = 'SELECT p.id, p.topic_id, p.post, p.author, p.email, p.website, UNIX_TIMESTAMP(p.date) AS date,
				  t.title AS topic_title,
				  t.slug AS topic_slug,
				  t.sticky AS topic_sticky,
				  t.closed AS topic_closed
				FROM '.Kohana::config('pianissiboard.table_prefix').'posts p
				  INNER JOIN '.Kohana::config('pianissiboard.table_prefix').'topics t
				  ON p.topic_id = t.id ';

		// One specific post id
		if (isset($config['id']))
		{
			if ((int) $config['id'] < 1)
				return FALSE;

			$where[] = 'p.id = '.(int) $config['id'];
		}

		// Filter on topic id
		if (isset($config['topic_id']))
		{
			if ((int) $config['topic_id'] < 1)
				return FALSE;

			$where[] = 'p.topic_id = '.(int) $config['topic_id'];
		}

		// Merge conditions
		if ( ! empty($where))
		{
			$sql.= 'WHERE '.implode(' AND ', $where).' ';
		}

		// Order by date
		$sql.= 'ORDER BY date ';

		// Active topics first
		if (isset($config['order']))
		{
			$sql.= strtoupper($config['order']).' ';
		}



		// Add LIMIT
		if (isset($config['limit']))
		{
			$sql.= 'LIMIT '.(int) $config['limit'].' ';

			// Add OFFSET
			if (isset($config['offset']))
			{
				$sql.= 'OFFSET '.(int) $config['offset'];
			}
		}

		return $this->db->query($sql);
	}

	/**
	 * Gets a single post.
	 *
	 * @param   integer  post id
	 * @return  array|FALSE
	 */
	public function get_by_id($post_id)
	{
		if (($result = $this->get(array('id' => $post_id))) === FALSE)
			return FALSE;

		return $result->current();
	}

	/**
	 * Counts all posts, or total posts in one topic.
	 *
	 * @param   integer  topic id
	 * @return  integer
	 */
	public function count($topic_id = FALSE)
	{
		// Build query
		$sql = 'SELECT COUNT(1) AS count FROM '.Kohana::config('pianissiboard.table_prefix').'posts ';

		// Count posts from one topic
		if ($topic_id !== FALSE)
		{
			$sql.= 'WHERE topic_id = '.(int) $topic_id;
		}

		return (int) $this->db->query($sql)->current()->count;
	}

	/**
	 * Add a post to a topic.
	 *
	 * @param   array    post data with keys matching fields
	 * @return  integer  insert id
	 */
	public function add($post)
	{
		return $this->db->query
		(
			'INSERT INTO '.Kohana::config('pianissiboard.table_prefix').'posts (topic_id, post, author, email, website, date) VALUES (?, ?, ?, ?, ?, NOW())',
			(int) $post['topic_id'], $post['post'], $post['author'], $post['email'], $post['website']
		)
		->insert_id();
	}

	/**
	 * Generates the full URL that links to a specific post in a topic.
	 *
	 * @param   integer  post id
	 * @param   integer  topic id
	 * @return  string|FALSE
	 */
	public function url($post_id, $topic_id = FALSE)
	{
		// Find topic id first
		if ($topic_id === FALSE)
		{
			if (($post = $this->get_by_id($post_id)) === FALSE)
				return FALSE;

			$topic_id = $post->topic_id;
		}

		// Load all posts from topic
		if (($posts = $this->get(array('topic_id' => $topic_id))) === FALSE)
			return FALSE;

		// Determine position of post within topic to calculate page number
		foreach ($posts as $position => $post)
		{
			if ($post->id == $post_id)
			{
				$page = (int) floor($position++ / Kohana::config('pianissiboard.posts_per_page')) + 1;
				break;
			}
		}

		// Post id not found within topic
		if (empty($page))
			return FALSE;

		// Generate URL
		return url::site('pianissiboard/topic/'.$topic_id.'/'.$post->topic_slug.'/page/'.$page.'#post-'.$post_id);
	}

	public function edit() {}
	public function delete() {}

}